package com.ebelter.bodyfatscale.ui.activity;

import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.ebelter.bodyfatscale.R;
import com.ebelter.bodyfatscale.adapter.RegisterPagerAdapter;
import com.ebelter.bodyfatscale.common.AppDateLitConstants;
import com.ebelter.bodyfatscale.model.Birthday;
import com.ebelter.bodyfatscale.model.RegisterInfo;
import com.ebelter.bodyfatscale.moudules.https.NetUtils;
import com.ebelter.bodyfatscale.moudules.https.interfaces.HttpResponse;
import com.ebelter.bodyfatscale.moudules.https.response.RegisterResponse;
import com.ebelter.bodyfatscale.ui.pager.register.BasePager;
import com.ebelter.bodyfatscale.ui.pager.register.BirthdayPager;
import com.ebelter.bodyfatscale.ui.pager.register.HeightPager;
import com.ebelter.bodyfatscale.ui.pager.register.RegisterPager;
import com.ebelter.bodyfatscale.ui.pager.register.SexPager;
import com.ebelter.bodyfatscale.util.KeyBoardShowListener;
import com.ebelter.bodyfatscale.util.MD5Utils;
import com.ebelter.bodyfatscale.util.ToastUtil;
import com.ebelter.bodyfatscale.util.VerifyUtils;
import com.ebelter.bodyfatscale.util.ViewUtils;
import com.ebelter.btlibrary.util.ULog;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 注册Activity，包含用户信息录入，账号密码设置
 */

public class RegisterActivity extends BaseActivity implements ViewPager.OnPageChangeListener {

    private static final String TAG = "RegisterActivity";


    @BindView(R.id.iv_back_register)
    ImageView iv_back_register;

    @BindView(R.id.vp_register)
    ViewPager vpRegister;


    @BindView(R.id.btn_next_register)
    TextView btn_next_register;

    private List<BasePager> pagers;
    private int curIndex;
    private int mHeight = 176;
    private int mSex = 0;//0男1女
    private Birthday mBirthday;
    private RegisterInfo mRegisterInfo;


    @Override
    protected int loadLayoutById() {
        return R.layout.activity_register;
    }

    KeyBoardShowListener keyBoardShowListener = new KeyBoardShowListener(this);
    @Override
    protected void initViews() {
    //监听软键盘的状态
        keyBoardShowListener.setKeyboardListener(

                new KeyBoardShowListener.OnKeyboardVisibilityListener() {
                    @Override
                    public void onVisibilityChanged(boolean visible) {
                        if (visible) {
                            //软键盘已弹出
                            ULog.e(TAG,"----------软键盘已弹出");
                            ViewUtils.hideView(btn_next_register);

                        } else {
                            //软键盘未弹出
                            ULog.e(TAG,"----------软键盘未弹出");
                            ViewUtils.displayView(btn_next_register);
                        }
                    }
                }, RegisterActivity.this);


    }
    @Override
    protected void initData() {
        if (pagers == null) {
            pagers = new ArrayList<>();
        } else {
            pagers.clear();
        }
        pagers.add(new HeightPager(this,mHeight));
        pagers.add(new SexPager(this,mSex));
        pagers.add(new BirthdayPager(this));
        pagers.add(new RegisterPager(this));


        vpRegister.setAdapter(new RegisterPagerAdapter(pagers));
        vpRegister.setOffscreenPageLimit(pagers.size());
        vpRegister.addOnPageChangeListener(this);
    }

    private void setNextBtText(int curIndex) {
        btn_next_register.setText(curIndex < 3 ? getString(R.string.next) : getString(R.string.done));
    }


    //设置下一步按钮是否可以用
    public void setbtn_next_register(boolean enable){
        btn_next_register.setEnabled(enable);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK) { //屏蔽返回键
            btClick(iv_back_register);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @OnClick({R.id.iv_back_register, R.id.btn_next_register})
    public void btClick(View view) {

        if (view.getId()==R.id.btn_next_register){
            HeightPager mHeightPager = (HeightPager) pagers.get(0);
            int value = mHeightPager.getHeight();
            if (value>= AppDateLitConstants.HEIGHT_MIN&&value<=AppDateLitConstants.HEIGHT_MAX){

            }else {
                    ToastUtil.showGravity(R.string.Please_enter_a_value_between_20_and_250_height, Gravity.CENTER);
                    return;
            }
        }


        int index = curIndex;
        switch (view.getId()) {
            case R.id.iv_back_register:
                index--;
                if (index < 0) {
                    finish();
                    return;
                }
                break;
            case R.id.btn_next_register:
                index++;
                if (index > pagers.size()) index = pagers.size();
                break;
        }
       // ULog.i(TAG, "curIndex = " + curIndex + "--- index = " + index);
        vpRegister.setCurrentItem(index);
        curIndex = index;
        setNextBtText(curIndex);
        if (curIndex>=4&&view.getId()==R.id.btn_next_register){
            curIndex=3;
            doneBtClick();
        }
    }



    private void doneBtClick() {
        ULog.i(TAG,"-----------DoneBtClick-----");
        HeightPager mHeightPager = (HeightPager) pagers.get(0);
        mHeight = mHeightPager.getHeight();

        SexPager mSexPager = (SexPager) pagers.get(1);
        mSex = mSexPager.getSexValue();

        BirthdayPager mBirthdayPager = (BirthdayPager) pagers.get(2);
        mBirthday = mBirthdayPager.getBirthday();

        RegisterPager mRegisterPager = (RegisterPager) pagers.get(3);
        mRegisterInfo = mRegisterPager.getRegisterInfo();

        ULog.i(TAG,"----------height="+mHeight+" sex="+mSex+"----"+mBirthday+"  -----  "+mRegisterInfo);


        if (mHeight< AppDateLitConstants.HEIGHT_MIN||mHeight>AppDateLitConstants.HEIGHT_MAX){
            ToastUtil.show(R.string.Please_enter_a_value_between_20_and_250_height);
            mHeightPager.shake_etHeight();
            return;
        }
        if (TextUtils.isEmpty(mRegisterInfo.getName())){
            ToastUtil.show(R.string.Nikename_cannot_be_empty);
            mRegisterPager.shake_etName();
            return;
        }


        if (mRegisterInfo.getName().length()>20){
            ToastUtil.show(R.string.nikename_over_tip);
            mRegisterPager.shake_etName();
            return;
        }

        if (TextUtils.isEmpty(mRegisterInfo.geteMail())){
            ToastUtil.show(R.string.Email_must_not_be_empty);
            mRegisterPager.shake_etMail();
            return;
        }
        if (!VerifyUtils.emailFormat(mRegisterInfo.geteMail())){
            ToastUtil.show(R.string.Incorrect_email_format);
            mRegisterPager.shake_etMail();
            return;
        }

        if (TextUtils.isEmpty(mRegisterInfo.geteMailCode())){
            ToastUtil.show(R.string.Mail_verification_code_cannot_be_empty);
            mRegisterPager.shake_etMailCode();
            return;
        }

        if (TextUtils.isEmpty(mRegisterInfo.getPwd())){
            ToastUtil.show(R.string.The_Password_cannot_be_empty);
            mRegisterPager.shake_etPwd();
            return;
        }

        if (mRegisterInfo.getPwd().length()<6){
            ToastUtil.show(R.string.psw_less_tip);
            mRegisterPager.shake_etPwd();
            return;
        }
        if (mRegisterInfo.getPwd().length()>20){
            ToastUtil.show(R.string.psw_over_tip);
            mRegisterPager.shake_etPwd();
            return;
        }

        if (!TextUtils.equals(mRegisterInfo.getPwd(),mRegisterInfo.getRepwd())){
            ToastUtil.show(R.string.The_password_is_inconsistency_twice);//前后密码输入不一致
            mRegisterPager.shake_etPwd();
            return;
        }


        if (!NetUtils.available()){
            ToastUtil.show(R.string.Network_error);
            return;
        }


        //   TODO 请求后台是否注册成功，成功则直接登录，把用户信息传递给MainActivity，不成功则再提交注册一次


        ULog.i(TAG,"注册的名字="+mRegisterInfo.getName()+"----性别sex="+mSex+"---运动员类型="+ mRegisterInfo.getRole());

        showLoadingDialog("");

            NetUtils.getInstance().registerRequest(this,
                    mRegisterInfo.getName(),
                    mRegisterInfo.geteMail(),
                    MD5Utils.getMd5(mRegisterInfo.getPwd()),
                    mBirthday.getFatterDay(),
                    mHeight,
                    0,
                    mSex,
                    mRegisterInfo.getRole(),
                    mRegisterInfo.geteMailCode(),
                    1, new HttpResponse<RegisterResponse>() {
                        @Override
                        public void result(boolean isRequestSuccess, String requestDes, RegisterResponse registerResponse) {
                            dissLoadingDialog();
                            if (isRequestSuccess){
                                if (registerResponse.resultCode==0){
                                    ULog.e(TAG,"注册返回："+registerResponse.resultMessage);
                                    ToastUtil.show(R.string.Registered_successfully);
                                    //showRegisterDialog();
                                    startActivity(LoginActivity.class);
                                    finish();
                                }else if (registerResponse.resultCode==106){
                                    ToastUtil.show(R.string.Email_verification_code_has_expired);
                                }else if (registerResponse.resultCode==107){
                                    ToastUtil.show(R.string.Wrong_email_verification_code);
                                }else if (registerResponse.resultCode==103){
                                    ToastUtil.show(R.string.The_email_or_nickname_has_been_registered);
                                } else if (registerResponse.resultCode==110){
                                    ToastUtil.show(R.string.An_exception_occurred_on_the_server);
                                } else {
                                    ToastUtil.show(R.string.Registration_failed);
                                }
                            }else {
                                ToastUtil.show(R.string.Network_connection_error);
                            }
                        }
                    });



    }




    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        ULog.i(TAG, "---onPageSelected position = " + position);

    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }


}
